package iuhao.common.response;

import com.alibaba.fastjson.JSONObject;
import iuhao.common.constants.O2OResponseCode;
import iuhao.common.utils.DateUtil;


import java.util.ArrayList;


/**
 * Created by yanhao on 2017/10/12.
 */
public class O2OJSON extends JSONObject {
    public O2OJSON() {
        put("timestamp", DateUtil.getCurrentDate());
        put("code", O2OResponseCode.SUCCESS);
        put("success", true);
        put("error", false);
        put("message", "");
    }

    public void setError(int code, String message) {
        put("code", code);
        put("success", false);
        put("error", true);
        // put("data", new JSONObject());
        put("message", message);
    }

    public void success() {
        put("code", O2OResponseCode.SUCCESS);
        put("success", true);
        put("error", false);
    }

    public void setSuccessAndNullData() {
        success();
        put("data", new JSONObject());
    }

    public void setSuccessAndListNullData() {
        success();
        put("data", new ArrayList<>());
    }


    public void setData(Object data) {
        success();
        put("data", data);
    }

    /**
     * @return
     */
    public boolean hasError() {
        Boolean error = getBoolean("error");
        if (error != null && error) {
            return true;
        }
        return false;
    }

    @Override
    public Object put(String key, Object value) {
        if (key.equals("message") && value == null) {
            value = "";
        }
        return super.put(key, value == null ? new JSONObject() : value);
    }
}
